package com.chinaway.dsp.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.mina.core.session.IoSession;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import com.chinaway.dsp.conn.AssemblyPacket;
import com.chinaway.dsp.util.AccStatus;
import com.chinaway.dsp.util.CountBean;
import com.chinaway.dsp.util.Point;

public class BackAction implements Runnable{
	private Text log_info_text;
	private List<String> dataList;
	private Table csvTable;
	public CountBean cb;
	private Display display;
	private String sendStr="";
	private Button sendBtn;
	private Button send_stop_btn;
	private Button open_path_btn;
	private boolean send=false;
	private Spinner send_interval_spinner;
	private int interval;
	private Text imei_text;
	private Text lng_text;
	private Text lat_text;
	private Text speed_text;
	private Text course_text;
	private Text displaytime_text;
	private Spinner send_totaltime_spinner;
	private Spinner send_iterationtime_spinner;
	private Button send_this_btn;
	private Button send_iteration_btn;
	private Button acc_status_btn;
	private AccStatus as;
	private int device_type;
	private Button settime_btn;
	private Button custom_send_btn;
	private IoSession session;
	private int sendCount=1;
	private Browser browser;
	private String dspInterfaceTime;
	CallDspInterfaceAction callDIA;
	private boolean callDspInterface=true;
	private List<Point> lnglat = new ArrayList<Point>();
	
	@Override
	public void run() {
		while(send){
			System.out.print("");
			if("continue".equals(sendStr)){
				display.syncExec(new Runnable() {
		            public void run() {
		            	Date currentTime = new Date();
		            	String tmp="";
		            	if(null!=dataList && dataList.size()>0)
		            	{
		            		csvTable.setSelection(cb.count);
			            	tmp=dataList.get(cb.count);
			            	String[] four=tmp.split(",");
			            	String msg_lat=AssemblyPacket.toLngLat(four[0]);
			            	String msg_lng=AssemblyPacket.toLngLat(four[1]);
			            	String msg_speed=AssemblyPacket.toSpeed(four[2]);
			            	String msg_course=AssemblyPacket.toCourse(four[3]);
			            	cb.add();
			            	String msg_seq=AssemblyPacket.string2wordhex(String.valueOf(sendCount));	
		    	   		 	SimpleDateFormat formatter = new SimpleDateFormat("yy MM dd HH mm ss");
		    	   		 	SimpleDateFormat dspformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    	   		 	String dateString = formatter.format(currentTime);
		    	   		 	dspInterfaceTime = dspformatter.format(currentTime);
		    	   		 	String msg="";
		    	   		 	if(0==device_type)
		    	   		 		msg="7E 05 00 00 27 "+AssemblyPacket.toImei(imei_text.getText())+" "+msg_seq+" 1D "+AssemblyPacket.toAcc(as.getStatus())+" "+msg_lat+" "+msg_lng+" 00 00 "+msg_speed+" "+msg_course+" "+dateString+" 00 00 00 00 00 0E 08 30 00 01 BA 53 70 4C 11 C0 B9 7E";
		    	   		 	if(1==device_type)
		    					msg="7E 02 00 00 1C "+AssemblyPacket.toImei(imei_text.getText())+" "+msg_seq+" 00 00 00 00 "+AssemblyPacket.toGnnsAcc(as.getStatus())+" "+msg_lat+" "+msg_lng+" 00 00 "+msg_speed+" "+msg_course+" "+dateString+" B9 7E";
		    	   		 	byte[] mes = AssemblyPacket.transfer2Bytes(msg);
		    				setNewFlag(mes);
		    				byte[] message=AssemblyPacket.edit7d7e(mes);
		    				session.write(message);
		    				String sendmsg=AssemblyPacket.byteToString(message);
		    				System.out.println("msg="+sendmsg);
		    				SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    			 	String date = formatter1.format(currentTime);
		    			 	log_info_text.append(date+" 发送：\n"+sendmsg+"\n");
			            	if(cb.count==dataList.size()){
			            		log_info_text.append("数据发送完毕2"+"\n");
			            		sendBtn.setText("发送");
			            		send_stop_btn.setText("停止");
			            		acc_status_btn.setText("点火");
		    					as.setStatus(0);
			            		send_stop_btn.setEnabled(false);
			            		open_path_btn.setEnabled(true);
			            		send_interval_spinner.setEnabled(true);
			            		cb.count=0;
			            		//sendCount=1;
			            		dataList.clear();
			            		sendStr="stop";
								lng_text.setEnabled(true);
								lat_text.setEnabled(true);
								speed_text.setEnabled(true);
								course_text.setEnabled(true);
								displaytime_text.setEnabled(true);
								send_totaltime_spinner.setEnabled(true);
								send_iterationtime_spinner.setEnabled(true);
								send_this_btn.setEnabled(true);
								send_iteration_btn.setEnabled(true);
								settime_btn.setEnabled(true);
								custom_send_btn.setEnabled(true);
			            		send=false;
			            	}
		            	}else if(lnglat.size()>0){
		            		
		            		Point p=lnglat.get(cb.count);
		            		
		            		String msg_lat=AssemblyPacket.toLngLat(String.format("%.6f", lnglat.get(cb.count).getWgLat()));
			            	String msg_lng=AssemblyPacket.toLngLat(String.format("%.6f", lnglat.get(cb.count).getWgLon()));
			            	String msg_speed=AssemblyPacket.toSpeed("80");
			            	String msg_course=AssemblyPacket.toCourse("0");
			            	cb.add();
			            	String msg_seq=AssemblyPacket.string2wordhex(String.valueOf(sendCount));	
		    	   		 	SimpleDateFormat formatter = new SimpleDateFormat("yy MM dd HH mm ss");
		    	   		 	SimpleDateFormat dspformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    	   		 	String dateString = formatter.format(currentTime);
		    	   		 	dspInterfaceTime = dspformatter.format(currentTime);
		    	   		 	String msg="";
		    	   		 	if(0==device_type)
		    	   		 		msg="7E 05 00 00 27 "+AssemblyPacket.toImei(imei_text.getText())+" "+msg_seq+" 1D "+AssemblyPacket.toAcc(as.getStatus())+" "+msg_lat+" "+msg_lng+" 00 00 "+msg_speed+" "+msg_course+" "+dateString+" 00 00 00 00 00 0E 08 30 00 01 BA 53 70 4C 11 C0 B9 7E";
		    	   		 	if(1==device_type)
		    					msg="7E 02 00 00 1C "+AssemblyPacket.toImei(imei_text.getText())+" "+msg_seq+" 00 00 00 00 "+AssemblyPacket.toGnnsAcc(as.getStatus())+" "+msg_lat+" "+msg_lng+" 00 00 "+msg_speed+" "+msg_course+" "+dateString+" B9 7E";
		    	   		 	byte[] mes = AssemblyPacket.transfer2Bytes(msg);
		    				setNewFlag(mes);
		    				byte[] message=AssemblyPacket.edit7d7e(mes);
		    				session.write(message);
		    				String sendmsg=AssemblyPacket.byteToString(message);
		    				System.out.println("msg="+sendmsg);
		    				SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    			 	String date = formatter1.format(currentTime);
		    			 	log_info_text.append(date+" 发送：\n"+sendmsg+"\n");
		            		
		    			 	if(cb.count==lnglat.size()){
			            		log_info_text.append("数据发送完毕2"+"\n");
			            		sendBtn.setText("发送");
			            		send_stop_btn.setText("停止");
			            		acc_status_btn.setText("点火");
		    					as.setStatus(0);
			            		send_stop_btn.setEnabled(false);
			            		open_path_btn.setEnabled(true);
			            		send_interval_spinner.setEnabled(true);
			            		cb.count=0;
			            		//sendCount=1;
			            		lnglat.clear();
			            		sendStr="stop";
								lng_text.setEnabled(true);
								lat_text.setEnabled(true);
								speed_text.setEnabled(true);
								course_text.setEnabled(true);
								displaytime_text.setEnabled(true);
								send_totaltime_spinner.setEnabled(true);
								send_iterationtime_spinner.setEnabled(true);
								send_this_btn.setEnabled(true);
								send_iteration_btn.setEnabled(true);
								settime_btn.setEnabled(true);
								custom_send_btn.setEnabled(true);
			            		send=false;
			            	}
		            	}
						
		            	
		            	sendCount++;
		            	if(callDspInterface)
		            		sendMapLoc();
		            }
		        });
				try {
					Thread.currentThread();
					Thread.sleep(send_Interval_Time());  
		    	} catch (Exception e) {
		        }
			}
		}
			        
	}
	
	public void sendMapLoc(){
			String loc=callDIA.getCurrent(imei_text.getText(),dspInterfaceTime);
			System.out.println(loc);
			int i=loc.indexOf("null");
			if(-1==i){
				browser.execute("gcj02ToBD09("+loc.split(",")[0]+","+loc.split(",")[1]+","+loc.split(",")[2]+");");
			}else{
				callDspInterface=false;
			}
			
	}
	
	public void setCallDspInterface(boolean b){
		this.callDspInterface=b;
	}
	
	public void setDspInterface(CallDspInterfaceAction cdia){
		this.callDIA=cdia;
	}
	
	public void setImeiText(Text t){
		this.imei_text=t;
	}
	public void setLngText(Text t){
		this.lng_text=t;
	}
	public void setLatText(Text t){
		this.lat_text=t;
	}
	public void setSpeedText(Text t){
		this.speed_text=t;
	}
	public void setCourseText(Text t){
		this.course_text=t;
	}
	public void setDisplaytimeText(Text t){
		this.displaytime_text=t;
	}
	public void setSendtotaltimeSpinner(Spinner s){
		this.send_totaltime_spinner=s;
	}
	public void setSenditerationtimeSpinner(Spinner s){
		this.send_iterationtime_spinner=s;
	}
	public void setSendthisBtn(Button b){
		this.send_this_btn=b;
	}
	public void setSenditerationBtn(Button b){
		this.send_iteration_btn=b;
	}
	public void setAcc_Status_Btn(Button b){
		this.acc_status_btn=b;
	}
	public void setDeviceType(int i){
		this.device_type=i;
	}
	public void setAccStatus(AccStatus as){
		this.as=as;
	}
	public void setSettimeBtn(Button b){
		this.settime_btn=b;
	}
	public void setCustom_Send_Btn(Button b){
		this.custom_send_btn=b;
	}
	
	public void setImportCsvList(List<String> l){
		this.dataList=l;
	}
	
	public void setCscTable(Table t){
		this.csvTable=t;
	}
	
	public void setCountBean(CountBean c){
		this.cb=c;
	}
	
	public void setMainUI(Display d){
		this.display=d;
	}
	
	public void setSendString(String s){
		this.sendStr=s;
	}
	
	public String getSendString(){
		return this.sendStr;
	}
	
	public void setSendBtn(Button b){
		this.sendBtn=b;
	}
	
	public void setStopBtn(Button b){
		this.send_stop_btn=b;
	}
	
	public void setOpenPathBtn(Button b){
		this.open_path_btn=b;
	}
	
	public void setSend(boolean b){
		this.send=b;
	}
	
	public void setLog_Info_Text(Text t){
		this.log_info_text=t;
	}
	
	public void setSend_Interval_Spinner(Spinner s){
		this.send_interval_spinner=s;
	}
	
	public void setSend_Interval_Time(int i){
		this.interval=i;
	}
	
	public int send_Interval_Time(){
		return interval*1000;
	}
	
	public void setSendSession(IoSession s){
		this.session=s;
	}
	
	public void setBrowser(Browser b){
		this.browser=b;
	}
	
	public void setRouteList(List l){
		this.lnglat=l;
	}
	
	private void setNewFlag(byte[] bs) {
		byte[] da = new byte[bs.length - 15];
		System.arraycopy(bs, 13, da, 0, da.length);
		//ctbox校验位
		//bs[bs.length - 4] = setNewFlagSub(da);
		//然后gnns校验位
		int idx = bs.length - 2;  
		bs[idx] = bs[1];
		for (int j=2;j<idx;j++) 
			bs[idx] ^= bs[j];
	}
	
}
